package com.rongc.client.freight.business.carrier.view.activity;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.core.utils.SystemUtil;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.model.ProvinceList;
import com.rongc.client.freight.base.model.TipTemp;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.activity.MapGdActivity;
import com.rongc.client.freight.base.view.adapter.RecyclerBaseAdapter;
import com.rongc.client.freight.base.view.widget.CJRow.ARResponse;
import com.rongc.client.freight.base.view.widget.CJRow.CJRow;
import com.rongc.client.freight.base.view.widget.CJRow.CJRowListener;
import com.rongc.client.freight.base.view.widget.CJRow.CustomCJRowAdapter;
import com.rongc.client.freight.base.view.widget.CJRow.ViewBinder;
import com.rongc.client.freight.base.view.widget.SpaceItemDecoration;
import com.rongc.client.freight.base.view.widget.wheelwidget.Time2PickerView;
import com.rongc.client.freight.business.carrier.buz.CarrierBuz;
import com.rongc.client.freight.business.carrier.model.ConveyanceDic;
import com.rongc.client.freight.business.carrier.request.api.CarListApi;
import com.rongc.client.freight.business.carrier.request.api.ConveyancePubApi;
import com.rongc.client.freight.business.carrier.view.adapter.RecyclerChoiceConveyanceAdapter;
import com.rongc.client.freight.business.mine.model.CarBean;
import com.rongc.client.freight.utils.UtilMethod;
import com.rongc.client.freight.utils.dic.IField;
import com.rongc.client.freight.utils.dic.impl.Field;
import com.rongc.client.freight.utils.dic.impl.Table;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by ccqx on 2017/7/1.
 */

public class ConveyanceCreateActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.cjrow)
    CJRow mRow;
    @Bind(R.id.recycler)
    RecyclerView mRecycler;
    RecyclerChoiceConveyanceAdapter mAdapter;
    List<CarBean> carBeanList;

    CustomCJRowAdapter baseAdapter;
    Table table_base;
    ARResponse response;
    Time2PickerView pvOptionsProvince;
    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:

                try{
                    prepare();
                    ConveyancePubApi p = new ConveyancePubApi(new ConveyancePubApi.ConveyancePubParams(response.getData()),
                            respWorkersListener, errorListener);
                    RequestManager.getInstance().call(p);
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }

                break;
        }
    }

    void prepare() throws RegexException {
        if(!RegexUtil.checkNotNull(response.getValue("loadTime"))){
            throw new RegexException("请选择装货时间");
        }else if(!RegexUtil.checkNotNull(response.getValue("startPlace"))){
            throw new RegexException("请选择出发地");
        }else if(!RegexUtil.checkNotNull(response.getValue("endPlace"))){
            throw new RegexException("请选择目的地");
        }else if(!RegexUtil.checkNotNull(response.getValue("truckId"))){
            throw new RegexException("请选择车辆");
        }

    }

    Response.Listener<CarBean[]> respCarListListener = new Response.Listener<CarBean[]>() {

        @Override
        public void onResponse(CarBean[] response) {
            if (HandleCode.requestSuccess()) {
                if(response != null && response.length != 0){
                    carBeanList.clear();
                }
                for (int i = 0; i < response.length; i++) {
                    carBeanList.add(response[i]);
                }
                mAdapter.notifyDataSetChanged();
            } else {
                UtilMethod.dismissProgressDialog(ConveyanceCreateActivity.this);
            }
        }
    };

    Response.Listener<NullResult> respWorkersListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast(HandleCode.headerMessage);
                finish();
            } else {
                UtilMethod.dismissProgressDialog(ConveyanceCreateActivity.this);
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(ConveyanceCreateActivity.this);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case  ConveyanceDic.ResultType.CAR_TYPE:
                    CarBean carBean = (CarBean) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("truckId",carBean.getId());
                    baseAdapter.notifyDataSetChanged();
                    break;
                case ConveyanceDic.ResultType.DEPARTURE_TYPE:
                    TipTemp result = (TipTemp) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("startPlace",result.getAddress());
                    baseAdapter.setFieldvalue("startLon",result.getLongitude() +"");
                    baseAdapter.setFieldvalue("startLat",result.getLatitude() +"");
                    baseAdapter.notifyDataSetChanged();
                    break;
                case ConveyanceDic.ResultType.DESTINATION_TYPE:
                    result = (TipTemp) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("endPlace",result.getAddress());
                    baseAdapter.setFieldvalue("endLon",result.getLongitude() +"");
                    baseAdapter.setFieldvalue("endLat",result.getLatitude() +"");
                    baseAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void initView() {
        initToolbar(R.string.conveyance_create_title);
    }

    @Override
    public void initData() {
        pvOptionsProvince = new Time2PickerView(this);
        response = CarrierBuz.getMockBaseResponse();
        table_base = CarrierBuz.getJBXXTable(this);
        baseAdapter = new CustomCJRowAdapter(this, mRow,table_base, response);
        mRow.setAdapter(baseAdapter);

        carBeanList = new ArrayList<>();
        mAdapter = new RecyclerChoiceConveyanceAdapter(this,carBeanList);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(this,1);
        mRecycler.addItemDecoration(new SpaceItemDecoration(SystemUtil.dip2px(this,1f)));
        mRecycler.setLayoutManager(mGridLayoutManager);
        mRecycler.setAdapter(mAdapter);
        mAdapter.setChoiseMode(AbsListView.CHOICE_MODE_SINGLE);
        mAdapter.setChoiceListener(new RecyclerBaseAdapter.OnItemClickListener<CarBean>() {
            @Override
            public void onItemClick(View view, int position, CarBean data) {
                baseAdapter.setFieldvalue("truckId",data.getId());
                baseAdapter.notifyDataSetChanged();
            }
        });

        baseAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, int position, String from) {
                if("truckId".equals(from)){
                    if(carBeanList != null)
                        for (CarBean bean : carBeanList) {
                            if((data.equals(bean.getId()))){
                                ((TextView)view.findViewById(R.id.lablevalue)).setText(bean.getModel());
                                break;
                            }
                        }
                }
                return false;
            }
        });

        baseAdapter.setCJRowListener(new CJRowListener() {
            @Override
            public boolean seedAction(int location, Field field, Object obj) {
                if("truckId".equals(field.getFieldName())){
//                    ActivityUtils.startActivityForResult(ConveyanceCreateActivity.this,CarModeActivity.class, SupplyDic.ResultType.Model_TYPE);
                    if(mRecycler.getVisibility() == View.VISIBLE)
                        mRecycler.setVisibility(View.INVISIBLE);
                    else
                        mRecycler.setVisibility(View.VISIBLE);
                    return true;
                }
                return false;
            }

            @Override
            public boolean activityAction(Field field, Object obj) {
                if("startPlace".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(ConveyanceCreateActivity.this,MapGdActivity.class, ConveyanceDic.ResultType.DEPARTURE_TYPE);
                }else if("endPlace".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(ConveyanceCreateActivity.this,MapGdActivity.class, ConveyanceDic.ResultType.DESTINATION_TYPE);
                }else if("truckId".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(ConveyanceCreateActivity.this,ConveyanceCarActivity.class, ConveyanceDic.ResultType.CAR_TYPE);
                }
                return true;
            }

            @Override
            public boolean popupWindowAction(final IField field, Object obj) {
                if("loadTime".equals(field.getFieldName())){
                    SystemUtil.hideSystemKeyboad(ConveyanceCreateActivity.this);
                    pvOptionsProvince.setPicker(ProvinceList.getOptions1Items(), ProvinceList.getOptions2Items(), ProvinceList.getOptions3Items(), true);
                    pvOptionsProvince.setCyclic(false, false, false);
                    pvOptionsProvince.setSelectOptions(0, 0, 0);
                    pvOptionsProvince.setOnoptionsSelectListener(new Time2PickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {
                            //返回的分别是三个级别的选中位置
                            String tx = ProvinceList.getOptions1Items().get(options1).getName()+" "
                                    + ProvinceList.getOptions2Items().get(option2)+ ":"
                                    + ProvinceList.getOptions3Items().get(options3)+ ":00";
                            baseAdapter.setFieldvalue(field.getFieldName(),tx);
                            baseAdapter.notifyDataSetChanged();
                        }
                    });
                    pvOptionsProvince.show();
                }
                return true;
            }
        });

        RequestManager.getInstance().call(new CarListApi(
                new CarListApi.CarListParams(UniApplication.getInstance().getUserInfo().getUserId()),
                respCarListListener, errorListener));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_conveyance_create;
    }
}
